package chapter14.section5;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 程序14-9a：新的LoginPanel，添加了按钮事件监听 User是一个表示登录用户的实体类
 */
public class LoginPanel extends JPanel implements ActionListener {
    // 在构造方法之外声明两个输入组件成员，主要是为了在构造方法之外能够得到输入内容
    JTextField txtName;
    JPasswordField txtPwd;
    MainFrame mfrm;// 用来引用主窗口

    public LoginPanel(MainFrame mfrm) {
        super();
        this.mfrm = mfrm;
        Box box1 = Box.createHorizontalBox();
        JLabel lblName = new JLabel("登录账号:");
        txtName = new JTextField(20);
        box1.add(lblName);
        box1.add(Box.createHorizontalStrut(20));
        box1.add(txtName);
        Box box2 = Box.createHorizontalBox();
        JLabel lblPwd = new JLabel("登录密码:");
        txtPwd = new JPasswordField(20);
        box2.add(lblPwd);
        box2.add(Box.createHorizontalStrut(20));
        box2.add(txtPwd);

        Box box3 = Box.createHorizontalBox();
        JButton btnLogin = new JButton("登录");
        btnLogin.setActionCommand("login");// 指定按钮的动作命令
        btnLogin.addActionListener(this);
        box3.add(btnLogin);

        Box box = Box.createVerticalBox();
        box.add(box1);
        box.add(Box.createVerticalStrut(20));
        box.add(box2);
        box.add(Box.createVerticalStrut(20));
        box.add(box3);
        this.add(box);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().compareTo("login") == 0) {
            // 因为getPassword()返回的是字符数组，所以需要形成字符串
            User u = new User(txtName.getText(), new String(txtPwd.getPassword()));
            if (u.login()) {// 当系统验证了登录用户的合法身份后,通知主窗口切换界面
                mfrm.loadTransactionPanel();
            }
        }
    }
}